import React from 'react';
import _ from 'lodash';
import { Input, Col, Row, Form, Button, DatePicker, Select } from 'antd';
import styles from './index.less';

const FormItem = Form.Item;
const RangePicker = DatePicker.RangePicker;
const Option = Select.Option;

const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
};

const Keywords = ({
                      fd,
                      fdKey = 'keywords',
                      label = '关键字',
                      placeholder = '请输入查询关键字',
                  }) => {
    const key = fd(fdKey);
    return (
        <Col span={8}>
            <FormItem {...formItemLayout} label={label}>
                {key(
                    <Input placeholder={placeholder} />,
                )}
            </FormItem>
        </Col>
    );
};
const TimeRange = ({ fd }) => {
    const timeRange = fd('timeRange', { type: 'array' });
    return (
        <Col span={8}>
            <FormItem
                {...formItemLayout}
                label="时间区间"
            >
                {timeRange(
                    <RangePicker />
                )}
            </FormItem>
        </Col>
    );
};

const SelectStore = ({ fd, options, onSearch, onChange }) => {
    const storeId = fd('storeId');
    const search = (value) => {
        console.log('search', value);
        onSearch(value);
    };
    const change = (value) => {
        console.log('change', value);
        onChange(value);
    };
    const renderOpts = _.map(options, ({ storeId, storeName }) => (
        <Option
            key={storeId}
            value={storeId}
        >
            {storeName}
        </Option>
    ));
    return (
        <Col span={8}>
            <FormItem {...formItemLayout} label="店铺名称">
                {storeId(
                    <Select
                        placeholder="请输入店铺名称关键字"
                        showSearch
                        onSearch={search}
                        onChange={change}
                        allowClear
                    >
                        {renderOpts}
                    </Select>
                )}
            </FormItem>
        </Col>
    );
};

const SelectUser = ({ fd, options, onSearch, disabled }) => {
    const userId = fd('userId');
    const search = (value) => {
        console.log('search', value);
        onSearch(value);
    };
    const renderOpts = _.map(options, ({ userId, userName }) => (
        <Option
            key={userId}
            value={userId}
        >
            {userName}
        </Option>
    ));
    return (
        <Col span={8}>
            <FormItem {...formItemLayout} label="玩家昵称">
                {userId(
                    <Select
                        placeholder="请输入玩家昵称关键字"
                        showSearch
                        onSearch={search}
                        allowClear
                        disabled={disabled}
                    >
                        {renderOpts}
                    </Select>
                )}
            </FormItem>
        </Col>
    );
};

const PayType = ({ fd }) => {
    const payType = fd('payType');
    return (
        <Col span={8}>
            <FormItem {...formItemLayout} label="支付方式">
                {payType(
                    <Select
                        placeholder="请选择支付方式"
                        allowClear
                    >
                        <Option value="wxpay">微信支付</Option>
                        <Option value="offlinePay">线下代收</Option>
                    </Select>
                )}
            </FormItem>
        </Col>
    );
};

const OrderType = ({ fd }) => {
    const orderType = fd('orderType');
    return (
        <Col span={8}>
            <FormItem {...formItemLayout} label="订单类型">
                {orderType(
                    <Select
                        placeholder="请选择订单类型"
                        allowClear
                    >
                        <Option value="1">充值</Option>
                        <Option value="2">畅玩套餐</Option>
                    </Select>
                )}
            </FormItem>
        </Col>
    );
};

const TradeType = ({ fd }) => {
    const tradeType = fd('tradeType');
    return (
        <Col span={8}>
            <FormItem {...formItemLayout} label="交易类型">
                {tradeType(
                    <Select
                        placeholder="请选择交易类型"
                        allowClear
                    >
                        <Option value="chongzhi">充值</Option>
                        <Option value="xiaofei">消费</Option>
                    </Select>
                )}
            </FormItem>
        </Col>
    );
};

export default Form.create()((props) => {
    const {
        form: {
            resetFields,
            validateFields,
            getFieldDecorator: fd,
            getFieldValue: gfv,
        },
        onSubmit,
        onStoreSearch = v => v,
        storesData = [],
        onUserSearch = v => v,
        usersData = [],
        config = [],
        initFd = {},
    } = props;
    if (_.isEmpty(config)) {
        return null;
    }
    const handleSearch = () => {
        validateFields((err, values) => {
            _.forEach(values, (v, k) => {
                if (!v) {
                    values[k] = '';
                }
            });
            if (values.timeRange && !_.isEmpty(values.timeRange)) {
                values.from = `${values.timeRange[0].format('YYYY-MM-DD')} 00:00:00`;
                values.to = `${values.timeRange[1].format('YYYY-MM-DD')} 23:59:59`;
            } else {
                values.from = '';
                values.to = '';
            }
            delete values.timeRange;
            onSubmit(values);
        });
    };
    const handleReset = () => {
        resetFields();
        handleSearch();
    };
    const clearUser = () => {
        resetFields(['userId']);
    };
    const storeChange = () => {
        clearUser();
    };
    const storeSearch = (keyword) => {
        onStoreSearch(keyword);
    };
    const userSearch = (keyword) => {
        onUserSearch(keyword);
    };
    const renderForm = (conf) => {
        if (!_.isEmpty(initFd)) {
            _.forEach(initFd, (initialValue, key) => {
                fd(key, {
                    initialValue,
                });
            });
        }
        const hasStore = gfv('storeId');
        return _.map(conf, (c, i) => {
            const baseProps = {
                key: `${c}_${i}`,
                fd,
            };
            switch (c) {
                case 'timeRange': {
                    return <TimeRange {...baseProps} />;
                }
                case 'payType': {
                    return <PayType {...baseProps} />;
                }
                case 'orderType': {
                    return <OrderType {...baseProps} />;
                }
                case 'tradeType': {
                    return <TradeType {...baseProps} />;
                }
                case 'keywords': {
                    return <Keywords {...baseProps} />;
                }
                case 'storeId': {
                    return (
                        <SelectStore
                            {...baseProps}
                            onChange={storeChange}
                            onSearch={storeSearch}
                            options={storesData}
                        />
                    );
                }
                case 'userId': {
                    return (
                        <SelectUser
                            {...baseProps}
                            disabled={!hasStore}
                            onSearch={userSearch}
                            options={usersData}
                        />
                    );
                }
                default: {
                    if (_.isObject(c)) {
                        return (
                            <Keywords
                                {...baseProps}
                                {...c}
                            />
                        );
                    }
                    return null;
                }
            }
        });
    };

    return (
        <Form className={styles.searchBar}>
            <Row>
                {renderForm(config)}
            </Row>

            <Row>
                <Col span={24} style={{ textAlign: 'right' }}>
                    <Button type="primary" onClick={handleSearch}>查询</Button>
                    <Button style={{ marginLeft: 8 }} onClick={handleReset}>
                        重置查询条件
                    </Button>
                </Col>
            </Row>
        </Form>
    );
});
